﻿var AJAXHelper = new Object();
    AJAXHelper.invoke       = _invoke;
    AJAXHelper.handleError  = _handleError;

function _invoke(methodURL, parameters, successFunction, data)
{
    /*
    If methodURL already specifies a page, i.e.: Default.aspx/logIn,
    discard current location page. Otherwise, consider location page.
    */

    /*
        if (httpVerb == undefined)
            httpVerb = "POST";
    */

    jQuery.support.cors = true;
      
    parameters = _parseParams(parameters);
    if ( isEmpty(parameters) )
        parameters = {};

    var baseUrl = window.location.pathname;
    if (window.location.pathname == "/")
        baseUrl = "Default.aspx";

    var arr = methodURL.split('/');
    if (arr.length > 1)
        methodURL = methodURL;
    else
        methodURL = baseUrl + "/" + methodURL;

    if ( methodURL.substring(0,1) == '/' )  /*if ( methodURL[0] == '/' )*/
        methodURL = methodURL.substring(1, methodURL.length);
   
    methodURL = methodURL.replace('../', '');

    var contentType = "application/json; charset-utf-8";

    var _successFunction = successFunction;
    if ( data != null && data != undefined )
        _successFunction = overloadFunction(successFunction, data);

    /* make AJAX call to the server.. */
    $.ajax
    (
        {
            url: _root + methodURL,
            data: parameters,
            datatype: "json",
            type: "POST",
            crossDomain: true,
            contentType: contentType,
            beforeSend: function (xhr, settings)
            {
                xhr.setRequestHeader("Content-type", contentType);
            },
            complete: function (resp)
            {
                /*
                    //var headers = resp.getAllResponseHeaders();
                    if ( !isEmpty(onResponseFunction) )
                        onResponseFunction.call(this, jQuery.parseJSON(resp.responseText.d));
                */
            },
            success: _successFunction,
            error: _handleError
        }
    );

    /* $.ajaxSetup({ async: false }); */
}

function _parseParams(parameters)
{
    if ( isEmpty(parameters) )
        return parameters;

    try
    {
        if ( parameters.indexOf( "{" ) == 0 )    
            return parameters;
    }
    catch (e)
    {
        
    }

    try
    {
        var params = "";
        var paramKeys = Object.keys(parameters);
        for (var i = 0; i < paramKeys.length; i++)
        {
            if (params.length > 0)
                params += ", ";
            params += toJSON(paramKeys[i]) + " : '" + toJSON(parameters[paramKeys[i]]) + "'";
        }
        params = "{ " + params + " }";
        return params;
    }
    catch (e)
    {

    }

    return null;
}

function _handleError(xmlHttpRequest, textStatus, errorThrown)
{
    handleError( xmlHttpRequest, textStatus, errorThrown );
}